package br.edu.ufabc.gtrnp.helppo.business;

import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import br.edu.ufabc.gtrnp.helppo.util.HelppoProperties;

public class EmailBusiness {
	private static EmailBusiness business = new EmailBusiness();
	
	private EmailBusiness(){
	}
	
	public static EmailBusiness getInstance(){
		return business;
	}

	public void enviaEmail(String email, String mensagem, String titulo)
			throws MessagingException, IOException, Exception {

		ResourceBundle propertiesHelppo = HelppoProperties.getInstance();
		Message message = new MimeMessage(getSession());

		message.addRecipient(RecipientType.TO, new InternetAddress(email));
		message.addFrom(new InternetAddress[] { new InternetAddress(
				propertiesHelppo.getString("email_remetente")) });

		message.setSubject(titulo);
		message.setContent(mensagem, "text/plain");

		Transport.send(message);
	}

	private Session getSession() throws Exception {
		Authenticator authenticator = new Authenticator();

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.submitter", authenticator
				.getPasswordAuthentication().getUserName());
		properties.setProperty("mail.smtp.auth", "true");

		properties.setProperty("mail.smtp.host", "mail.ufabc.edu.br");
		properties.setProperty("mail.smtp.port", "25");

		return Session.getInstance(properties, authenticator);
	}

}

class Authenticator extends javax.mail.Authenticator {
	private PasswordAuthentication authentication;

	public Authenticator() throws Exception {
		ResourceBundle propertiesHelppo = HelppoProperties.getInstance();
		String username = propertiesHelppo.getString("email_remetente");
		String password = propertiesHelppo.getString("senha_remetente");
		authentication = new PasswordAuthentication(username, password);
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return authentication;
	}
}
